package com.itmk.business.article.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.business.article.entity.Article;
import com.itmk.business.article.entity.Comment;
import com.itmk.business.article.entity.CommentManager;
import com.itmk.business.article.entity.CommentState;
import com.itmk.business.article.mapper.CommentManagerMapper;
import com.itmk.business.article.mapper.CommentMapper;
import com.itmk.business.article.service.ArticleService;
import com.itmk.business.article.service.CommentService;
import com.itmk.business.articleCategory.entity.ArticleCategory;
import com.itmk.business.articleCategory.service.ArticleCategoryService;
import com.itmk.constants.Constant;
import com.itmk.result.DataResult;
import com.itmk.utils.JwtTokenUtil;
import com.itmk.utils.PageUtil;
import com.itmk.utils.QiniuCloudUtil;
import com.itmk.vo.req.ArticleReqVO;
import com.itmk.vo.req.CommentManagerReqVO;
import com.itmk.vo.req.CommentReqVO;
import com.itmk.vo.resp.CommentManagerRespVO;
import com.itmk.vo.resp.PageRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/article")
@Api(tags = "文章管理")
public class ArticleController {
    @Autowired
    private QiniuCloudUtil qiniuCloudUtil;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleCategoryService articleCategoryService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentManagerMapper commentManagerMapper;

    @ApiOperation(value = "根据分类Id查询文章列表")
    @RequestMapping(value = "/getarticlebycategoryid",method = RequestMethod.POST)
    public DataResult getarticlesCategoryById(@RequestBody ArticleCategory articleCategory){
        List<Article> articles=articleService.getArticlesByCategoryId(articleCategory.getId());
        return DataResult.success(articles);
    }


    @ApiOperation(value = "保存文章")
    @RequestMapping(value = "/savearticle",method = RequestMethod.POST)
    public DataResult saveArticle(@RequestBody Article article){
        Long b=articleService.saveArticle(article);
        if(b>0){
            if(!articleService.SaveArticleTag(article)){
                return DataResult.getResult(300100,"更新文章标签失败!");
            }
            return DataResult.success(article.getId().toString());
        }else{
            return DataResult.getResult(300100,"保存失败!");
        }
    }

    @ApiOperation(value = "根据id获取文章")
    @RequestMapping(value = "/getarticlebyid",method = RequestMethod.POST)
    public DataResult getArticleById(@RequestBody ArticleReqVO vo){
        Article a=articleService.getArticleById(vo.getId());
        return DataResult.success(a);
    }

    @ApiOperation(value = "根据条件获取文章")
    @RequestMapping(value = "/getarticlelist",method = RequestMethod.POST)
    public DataResult getArticleList(@RequestBody ArticleReqVO vo){
        IPage<Article> page = new Page<>();
        page.setCurrent(vo.getCurrentPage());
        page.setSize(vo.getPageSize());
        IPage<Article> articles=articleService.getArticleList(page,vo);
        return DataResult.success(articles);
    }

    @ApiOperation(value = "更新文章")
    @RequestMapping(value = "/updatearticle",method = RequestMethod.POST)
    public DataResult updateArticle(@RequestBody Article article){
        Long b=articleService.updateArticle(article) ;
        if(b>0){
            if(!articleService.SaveArticleTag(article)){
                return DataResult.getResult(300100,"更新文章标签失败!");
            }
            return DataResult.success(article.getId().toString());
        }else{
            return DataResult.getResult(300100,"更新失败!");
        }
    }

    @ApiOperation(value = "显示首页文章")
    @RequestMapping(value = "/displayarticle",method = RequestMethod.POST)
    public DataResult displayArticle(@RequestBody Article article){
        Boolean b=articleService.displayArticle(article);
        if(b){
            return DataResult.success();
        }else{
            return DataResult.getResult(300100,"更新失败!");
        }
    }

    @ApiOperation(value = "删除文章")
    @RequestMapping(value = "/deletearticlebyid",method = RequestMethod.POST)
    public DataResult deleteArticleById(@RequestBody Article article){
        Boolean b=articleService.removeById(article.getId());
        if(b){
            return DataResult.success();
        }else{
            return DataResult.getResult(300100,"删除失败!");
        }
    }



    @ApiOperation(value = "上传主图")
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public DataResult uploadImg(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return DataResult.getResult(300100,"文件不能为空");
        }
        try {
            byte[] bytes = file.getBytes();
            String imageName = UUID.randomUUID().toString();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuCloudUtil.put64image(bytes, imageName);
                return DataResult.success(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            return DataResult.getResult(300100,"上传图片异常");
        }
        return DataResult.success();
    }

    @ApiOperation(value = "删除主图")
    @RequestMapping(value = "/deleteimg", method = RequestMethod.POST)
    public DataResult deletetImg(@RequestBody HashMap<String, String> map) {
        String name=map.get("name");
        try {
            Boolean flag=qiniuCloudUtil.delete(name); // 删除照片
            if (flag) {
                return DataResult.success();
            } else {
                return DataResult.getResult(300100, "删除失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DataResult.getResult(300100, "图片不存在或其它异常!");
        }

    }


    @ApiOperation(value = "保存评论")
    @RequestMapping(value = "/savecomment",method = RequestMethod.POST)
    public DataResult saveComment(@RequestBody Comment comment){
        Boolean b=commentService.save(comment);
        if(b){
            return DataResult.success();
        }else{
            return DataResult.getResult(300100,"保存失败!");
        }
    }

    @ApiOperation(value = "分页获取评论列表")
    @RequestMapping(value = "/getcommentList",method = RequestMethod.POST)
    public DataResult getCommentList(@RequestBody CommentReqVO vo){
        List<Object> resultList=this.commentMapper.getcommentListsByProcedure(vo);
        PageRespVO<Object> pageRespVO= PageUtil.getPageVo(resultList);
        return DataResult.success(pageRespVO);
    }

    @ApiOperation(value = "更新评论  包括屏蔽评论")
    @RequestMapping(value = "/updatecomment",method = RequestMethod.POST)
    public DataResult updateComment(@RequestBody Comment comment, HttpServletRequest request){
        Integer b=this.commentMapper.updateById(comment);
        String accessToken=request.getHeader(Constant.ACCESS_TOKEN);
        String userId= JwtTokenUtil.getUserId(accessToken);
        if(b>0){
            log.info("【{}】更新了文章【{}】的评论，评论者是{},内容是{}",userId,comment.getArticleId(),comment.getContactId(),comment.getContent());
            return DataResult.success();
        }else{
            return DataResult.getResult(300100,"评论更新失败!");

        }
    }

    @ApiOperation(value = "屏蔽评论")
    @RequestMapping(value = "/hidecomment",method = RequestMethod.POST)
    public DataResult hideComment(@RequestBody Comment comment, HttpServletRequest request){
        Integer b=this.commentMapper.updateById(comment);
        String accessToken=request.getHeader(Constant.ACCESS_TOKEN);
        String userId= JwtTokenUtil.getUserId(accessToken);
        if(b>0){
            log.info("【{}】更新了文章【{}】的评论，评论者是{},内容是{}",userId,comment.getArticleId(),comment.getContactId(),comment.getContent());
            this.commentManagerMapper.insert(new CommentManager(new Long(userId),comment.getCommentId(), CommentState.hide.getCode()));
            return DataResult.success();
        }else{
            return DataResult.getResult(300100,"评论更新失败!");

        }
    }

    @ApiOperation(value = "恢复评论")
    @RequestMapping(value = "/showcomment",method = RequestMethod.POST)
    public DataResult showComment(@RequestBody CommentManager cm, HttpServletRequest request){
        Comment comment=new Comment(cm.getCommentId(),true);
        Integer b=this.commentMapper.updateById(comment);
        String accessToken=request.getHeader(Constant.ACCESS_TOKEN);
        String userId= JwtTokenUtil.getUserId(accessToken);
        if(b>0){
            log.info("【{}】更新了文章【{}】的评论，评论者是{},内容是{}",userId,comment.getArticleId(),comment.getContactId(),comment.getContent());
            this.commentManagerMapper.updateById(new CommentManager(cm.getId(), CommentState.show.getCode()));
            return DataResult.success();
        }else{
            return DataResult.getResult(300100,"评论更新失败!");

        }
    }
    @ApiOperation(value = "获取评论管理列表")
    @RequestMapping(value = "/getcommentmanagerlist",method = RequestMethod.POST)
    public DataResult getCommentManagerList(@RequestBody CommentManagerReqVO vo){
        IPage<CommentManagerRespVO> page = new Page<>();
        page.setCurrent(vo.getCurrentPage());
        page.setSize(vo.getPageSize());
        IPage<CommentManagerRespVO> list=this.commentManagerMapper.getCommentManagerList(page,vo);
        return DataResult.success(list);
    }

    @ApiOperation(value = "获取单个评论的逐级列表")
    @RequestMapping(value = "/getcommentdetail",method = RequestMethod.POST)
    public DataResult getCommentDetail(@RequestBody Comment comment){
        this.commentManagerMapper.truncateTable();
        List<HashMap<String,Object>> result=this.commentManagerMapper.getCommentDetail(comment);
        return DataResult.success(result);
    }

}
